import React, { useState, useEffect } from "react";
import { Avatar, List } from "antd";
import { useAppSelector } from "../../app/hooks";
import ChatWindow from "./ChatWindow";
import styles from "./index.module.scss";

interface ChatProps {
  type: string;
  id: number | null;
  from: string;
  to: string;
  body: string;
}

export default function Chat() {
  const username = useAppSelector((state) => state.user.username);
  const [chatList, setChatList] = useState<Array<ChatProps>>([]);

  const data = [
    {
      id: 1,
      type: "mult",
      name: "群聊1",
      avatar: "https://joeschmoe.io/api/v1/random",
    },
    {
      id: 2,
      type: "mult",
      name: "群聊2",
      avatar: "https://joeschmoe.io/api/v1/random",
    },
    {
      id: 3,
      type: "priv",
      name: "大佬",
      avatar: "https://randomuser.me/api/portraits/men/7.jpg",
    },
  ];

  let wsUrl = "ws://127.0.0.1:8080/?name=" + username;
  const ws = new WebSocket(wsUrl);

  useEffect(() => {
    // 连接上
    ws.onopen = function (e) {
      console.log("客户端socket'开启");

      ws.send(
        JSON.stringify({
          type: "online",
          username,
        })
      );
    };

    // 收到服务端消息
    ws.onmessage = function (res) {
      const data = JSON.parse(res.data);
      console.log("收到消息", data);
      setChatList((pre) => [...pre, data]);
      // ws.close();
    };

    // 断开连接
    ws.onclose = function (e) {
      console.log("关闭", e);
    };

    // 连接出错
    ws.onerror = function (err) {
      console.log("出错", err);
    };

    return () => {
      ws.send(
        JSON.stringify({
          type: "offline",
          username,
        })
      );
      ws.close();
    };
  }, []);

  // 切换聊天
  const onChangeChat = (item: any) => {
    console.log("切换", item);
  };
  const onSendMsg = (data: any) => {
    console.log("接收到发送的信息：", data);

    ws.send(JSON.stringify(data));
  };

  return (
    <div className={styles.chat_room}>
      <div className={styles.chat_room_left}>
        <List
          itemLayout="horizontal"
          dataSource={data}
          renderItem={(item) => (
            <List.Item onClick={() => onChangeChat(item)}>
              <List.Item.Meta
                avatar={<Avatar src={item.avatar} />}
                title={<span>{item.name}</span>}
              />
            </List.Item>
          )}
        />
      </div>
      <div className={styles.chat_room_right}>
        <ChatWindow chatList={chatList} sendMsg={onSendMsg} />
      </div>
    </div>
  );
}
